package uk.co.kevinlockwood.kol.pages;

import java.util.ArrayList;
import java.util.List;

import uk.co.kevinlockwood.kol.JavaHelpers;
import uk.co.kevinlockwood.kol.droid.DroidHelpers;
import uk.co.kevinlockwood.kol.messages.KoLMessage;

public class NewChatMessages extends KoLPage {
	private List<KoLMessage> messages;
	private String lastcheck;

	// constructor
	public NewChatMessages(String lastcheck) {
		this.lastcheck = lastcheck;
		this.messages = new ArrayList<KoLMessage>();
		if (this.lastcheck == null) {
			this.lastcheck = "0";
		}
	}

	@Override
	public String pageName() {
		return "newchatmessages.php?lasttime="+lastcheck+"&afk=0";
	}

	public String getLastCheck() {
		return lastcheck;
	}
	public List<KoLMessage> getMesssages() {
		return messages;
	}

	private static String splitpattern = "<br>";

	@Override
	public void buildFromHtml(List<String> html) {
		for (String s : html) {
			// get the 'lastcheck' value, so that if the parsing fails, we don't fail again straight away by getting the same message
			lastcheck = JavaHelpers.substringToString(s, "<!--lastseen:", "-->");

			DroidHelpers.log("new chat messages [",s,"]");
			String[] ss = s.split(splitpattern);
			for (int i=0 ; i < ss.length-1 ; i++) {
				KoLMessage m;
				if (ss[i].endsWith(": ") && i<ss.length-1) {
					// special case for haiku
					m = KoLMessage.parse(ss[i] + ss[i+1]);
					i++;
				} else {
					m = KoLMessage.parse(ss[i]);
				}
				messages.add(m);
			}
		}
	}
}
